<?php

namespace App\Common\Util\Response;

use think\Response;

/**
 * 响应json
 */
class Json
{
    /**
     * @param mixed|null $data
     * @param int $code
     * @param string $msg
     */
    private mixed  $data = null;
    private int    $code = 200;
    private string $msg = 'success';


    /**
     * @param mixed|null $data
     * @param string     $message
     *
     * @return Response
     */
    public function success(mixed $data = null, string $message = 'success'): Response
    {
        return $this->body(200, $message, $data);
    }

    /**
     * @param array $data
     *
     * @return Response
     */
    public function raw(array $data): Response
    {
        return $this->response($data);
    }

    /**
     * @param string $message
     * @param int    $code
     *
     * @return Response
     */
    public function fail(string $message = 'fail', int $code = 202): Response
    {
        return $this->body($code, $message);
    }

    /**
     * @param int        $code
     * @param string     $message
     * @param mixed|null $data
     *
     * @return Response
     */
    public function body(int $code, string $message, mixed $data = null): Response
    {
        $this->data = $data;
        $this->code = $code;
        $this->msg  = $message;

        return $this->toJson();
    }


    /**
     * @return Response
     */
    private function toJson(): Response
    {
        return $this->response([
            'code' => $this->code,
            'data' => $this->data,
            'msg'  => $this->msg,
            'ts'   => time()
        ]);
    }

    /**
     * @param array $data
     *
     * @return Response
     */
    private function response(array $data): Response
    {
        return Response::create($data, \think\response\Json::class);
    }
}
